package com.youmingxing.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.youmingxing.AllStarApp;
import com.youmingxing.R;
import com.youmingxing.activity.AuditionSelectActivity;
import com.youmingxing.activity.WebViewActivity;
import com.youmingxing.adpter.MovieListAdapter;
import com.youmingxing.bean.Section;
import com.youmingxing.bean.Web;
import com.youmingxing.network.AllStarApi;
import com.youmingxing.network.BaseJsonHandler;
import com.youmingxing.utils.TimeUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;

/**
 * 单个电影
 *
 * @author evilyin(ChenZhixi)
 * @since 15/9/1
 */
public class MovieFragment extends Fragment {

    private View view;
    private ListView movieMainListView;
    private PtrClassicFrameLayout ptrClassicFrameLayout;
    private View headerView;

    private List<Section> sectionList = new ArrayList<>();
    private int movie_id;
    private String titleImageUrl;
    private String titleClickUrl;
    private int auditionStatus;
    private long timestamp;
    private int applyCount;
    private String statusTip;

    private MovieListAdapter adapter;

    public MovieFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            movie_id = bundle.getInt("id");
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_movie, container, false);
            movieMainListView = (ListView) view.findViewById(R.id.movie_main_list);
            ptrClassicFrameLayout = (PtrClassicFrameLayout) view.findViewById(R.id.ptr_layout);
            headerView = View.inflate(AllStarApp.getInstance(), R.layout.header_movie_main,
                    null);
            initData();
            movieMainListView.addHeaderView(headerView);

            ptrClassicFrameLayout.setLastUpdateTimeRelateObject(this);
            ptrClassicFrameLayout.disableWhenHorizontalMove(true);
            ptrClassicFrameLayout.setPtrHandler(new PtrHandler() {
                @Override
                public boolean checkCanDoRefresh(PtrFrameLayout ptrFrameLayout, View view, View view1) {
                    return PtrDefaultHandler.checkContentCanBePulledDown(ptrFrameLayout, view, view1);
                }

                @Override
                public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {
                    initData();
                }
            });
        }
        return view;
    }

    private void initData() {
        AllStarApi.getAuditionInfo(movie_id, new BaseJsonHandler(getContext()) {
            @Override
            public void onSuccessWithData(JSONObject response) {
                sectionList.clear();
                JSONObject data = response.optJSONObject("data");
                titleImageUrl = data.optString("title_img");
                titleClickUrl = data.optString("title_url");
                auditionStatus = data.optInt("audition_status");
                timestamp = data.optLong("begin_or_end_time");
                applyCount = data.optInt("apply_count");
                statusTip = data.optString("status_tip");
                initHeader();

                JSONArray array = data.optJSONArray("sections");
                for (int i = 0; i < array.length(); i++) {
                    Section section = new Section(array.optJSONObject(i));
                    sectionList.add(section);
                }
                adapter = new MovieListAdapter(getActivity(), sectionList);
                movieMainListView.setAdapter(adapter);

                ptrClassicFrameLayout.refreshComplete();

            }
        });
    }


    private void initHeader() {
        ImageView mainImage = (ImageView) headerView.findViewById(R.id.title_image);
        TextView assignedNumber = (TextView) headerView.findViewById(R.id.assigned_number);
        TextView leftDaysNumber = (TextView) headerView.findViewById(R.id.left_days_number);
        TextView leftDaysText = (TextView) headerView.findViewById(R.id.left_days_text);
        ImageView signButton = (ImageView) headerView.findViewById(R.id.sign_button);

        signButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), AuditionSelectActivity.class);
                intent.putExtra(AuditionSelectActivity.EXTRA_ID, movie_id);
                startActivity(intent);
            }
        });

        Glide.with(getActivity()).load(titleImageUrl).placeholder(R.drawable.default_16_9)
                .error(R.drawable.default_16_9).animate(R.anim.abc_fade_in).into(mainImage);
        if (!titleClickUrl.isEmpty()) {
            mainImage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), WebViewActivity.class);
                    intent.putExtra("web_page", Web.pages);
                    intent.putExtra("url", titleClickUrl);
                    getActivity().startActivity(intent);
                }
            });
        }
        assignedNumber.setText("已报名" + applyCount + "人");
        String timeString = TimeUtils.parseMilliSecond(timestamp - System
                .currentTimeMillis());
//        int index = timeString.indexOf("天");
//        if (index == -1) {
//            leftDaysNumber.setText("0");
//        } else {
//            leftDaysNumber.setText(timeString.substring(0, index));
//        }
        String timeNumber = timeString.replace("天", "").replace("小时", "").replace("分钟", "").replace
                ("秒", "");
        leftDaysNumber.setText(timeNumber);
        switch (auditionStatus) { // 海选状态 1 未开始 2 海选中 3 海选结束未出结果 4 海选结束结果已出
            case 1:
                leftDaysText.setText("剩余" + timeString);
                signButton.setImageResource(R.mipmap.su_1);
                break;
            case 2:
                leftDaysText.setText("剩余" + timeString);
                signButton.setImageResource(R.mipmap.btn_2);
                break;
            case 3:
                leftDaysNumber.setVisibility(View.GONE);
                leftDaysText.setText("");
                signButton.setImageResource(R.mipmap.su_3);
                break;
            case 4:
                leftDaysNumber.setVisibility(View.GONE);
                leftDaysText.setText("");
                signButton.setImageResource(R.mipmap.su_3);
                break;
            case 0:
                leftDaysNumber.setVisibility(View.GONE);
                leftDaysText.setText(statusTip);
                break;
            default:
                leftDaysText.setText("什么情况?");
                break;
        }
        if (!statusTip.isEmpty()) {
            leftDaysNumber.setVisibility(View.GONE);
            leftDaysText.setText(statusTip);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (view != null) {
            ((ViewGroup) view.getParent()).removeView(view);
        }
    }

}
